package com.zztl.infiniteBand.ui.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import butterknife.OnClick
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.yalantis.ucrop.UCrop
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.eventbus.AuditSuccessEvent
import com.zztl.infiniteBand.model.UploadFileBean
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.requestBean.CertificateRequest
import com.zztl.infiniteBand.presenter.CertificatePresenter
import com.zztl.infiniteBand.ui.view.dialog.PhotoPop
import com.zztl.infiniteBand.ui.view.mvpview.CertificateView
import com.zztl.infiniteBand.util.PermissionUtils
import com.zztl.infiniteBand.util.toast
import kotlinx.android.synthetic.main.activity_certification.*
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.IOException
import java.net.URI
import java.net.URISyntaxException

class CertificationActivity : BaseMvpActivity<CertificateView, CertificatePresenter>(), CertificateView, TextWatcher {


    private var holdPhoto: ImageView? = null
    private var frontPhoto: ImageView? = null
    private var reversePhoto: ImageView? = null

    lateinit var mEtType: TextView
    private var mPhotoPop: PhotoPop? = null
    private var mCardPop: PhotoPop? = null
    private val CAMERA = 10
    private val ALBUM = 20
    private var cardType = 1
    private var fileName: String? = null
    private var holdPath: String? = null
    private var frontPath: String? = null
    private var reversePath: String? = null
    private var mFile: File? = null
    private var mCropedFile: File? = null
    lateinit var mPresenter: CertificatePresenter
    private var mUri: Uri? = null

    lateinit var photoList: List<String>
    lateinit var cardTypeList: List<String>


    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            when (requestCode) {
                PermissionUtils.CODE_MULTI_PERMISSION -> showPhotoPop()
            }
        }
    }

    override fun setLayoutId(): Int = R.layout.activity_certification


    override fun initBase() {
        headerView!!.setBackgroundColor(Color.TRANSPARENT)
        setTitle(getString(R.string.实名认证))
        val tvType = item_voucher_type.findViewById<View>(R.id.tv_label) as TextView
        mEtType = item_voucher_type.findViewById<View>(R.id.et_user_id) as TextView
        tvType.text = getString(R.string.证件类型)
        mEtType.text = getString(R.string.中国大陆居民身份证)
        item_voucher_type.setOnClickListener { showCardPop() }


        val tvHoldlabel = item_hold.findViewById<View>(R.id.tv_label) as TextView
        holdPhoto = item_hold.findViewById<View>(R.id.iv_photo) as ImageView
        tvHoldlabel.text = getString(R.string.上传手持正面照)

        val tvFrontlabel = item_front.findViewById<View>(R.id.tv_label) as TextView
        frontPhoto = item_front.findViewById<View>(R.id.iv_photo) as ImageView
        tvFrontlabel.text = getString(R.string.上传证件正面照)


        val tvReverselabel = item_reverse.findViewById<View>(R.id.tv_label) as TextView
        reversePhoto = item_reverse.findViewById<View>(R.id.iv_photo) as ImageView
        tvReverselabel.text = getString(R.string.上传证件反面照)


        photoList = listOf(getString(R.string.拍照), getString(R.string.从相册中选取))
        cardTypeList = listOf(getString(R.string.中国大陆居民身份证), getString(R.string.护照), getString(R.string.港澳通行证)
                , getString(R.string.回乡证), getString(R.string.其他))

        item_realname.middleEdit.addTextChangedListener(this)
        item_voucher_num.middleEdit.addTextChangedListener(this)
    }


    override fun createPresenter(): CertificatePresenter {
        mPresenter = CertificatePresenter()
        return mPresenter
    }


    override fun afterTextChanged(s: Editable?) {
        s?.let {
            btn_submit.isEnabled = item_realname.middleEditStr.isNotEmpty() && item_voucher_num.middleEditStr.isNotEmpty()
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

    }


    @OnClick(R.id.btn_back, R.id.btn_submit, R.id.item_hold, R.id.item_front, R.id.item_reverse)
    fun click(view: View) {
        when (view.id) {
            R.id.btn_back -> finish()
            R.id.item_hold -> {
                fileName = "hold.jpeg"
                PermissionUtils.requestMultiPermissions(this, mPermissionGrant, PermissionUtils.CODE_UPLOAD_IMG)
            }
            R.id.item_front -> {
                fileName = "front.jpeg"
                PermissionUtils.requestMultiPermissions(this, mPermissionGrant, PermissionUtils.CODE_UPLOAD_IMG)
            }
            R.id.item_reverse -> {
                fileName = "reverse.jpeg"
                PermissionUtils.requestMultiPermissions(this, mPermissionGrant, PermissionUtils.CODE_UPLOAD_IMG)
            }
            R.id.btn_submit -> {
                val name = item_realname.middleEditStr
                val cardNum = item_voucher_num.middleEditStr
                if (mPresenter.check(name, cardNum, frontPath, reversePath, holdPath)) {
                    mPresenter.certificate(CertificateRequest(cardNum, name, cardType.toString(), RetorfitServiceManger.BASE_IMG_URL + holdPath!!,
                            RetorfitServiceManger.BASE_IMG_URL + frontPath!!, RetorfitServiceManger.BASE_IMG_URL + reversePath!!), this)
                }
            }

            else -> {
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant)

    }


    private fun showCardPop() {
        if (null != mCardPop) {
            mCardPop = null
        }
        mCardPop = PhotoPop(this, object : PhotoPop.PopOnItemClickListener {
            override fun onItemClick(position: Int) {
                mEtType!!.text = cardTypeList[position]
                mCardPop!!.dismiss()
                when (position) {
                    0 -> cardType = 1
                    1 -> cardType = 2
                    2 -> cardType = 3
                    3 -> cardType = 4
                    4 -> cardType = 0
                }
            }
        }, 1, false).setData(cardTypeList)
        mCardPop!!.showPopupWindow()
    }

    private fun showPhotoPop() {
        if (mPhotoPop != null) {
            mPhotoPop = null
        }
        mPhotoPop = PhotoPop(this, object : PhotoPop.PopOnItemClickListener {
            override fun onItemClick(position: Int) {
                mPhotoPop!!.dismiss()
                val mFileDir = File(Environment.getExternalStorageDirectory().absolutePath + "/GVC/Image")
                if (!mFileDir.exists()) {
                    mFileDir.mkdirs()
                }
                mFile = File(mFileDir.absolutePath,
                        System.currentTimeMillis().toString() + fileName!!)
                if (!mFile!!.exists()) {
                    try {
                        mFile!!.createNewFile()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }

                }

                try {
                    if (position == 0) {

                        //拍照
                        val intent = Intent("android.media.action.IMAGE_CAPTURE")
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            val photoURI = FileProvider.getUriForFile(this@CertificationActivity,
                                    "com.zztl.infiniteBand.fileprovider",
                                    mFile!!)
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile))
                        }
                        showActivityForResult(intent, CAMERA)
                    } else if (position == 1) {
                        //从相册中选择
                        val intent = Intent()
                        intent.type = "image/*"
                        intent.action = Intent.ACTION_GET_CONTENT
                        intent.addCategory(Intent.CATEGORY_OPENABLE)
                        showActivityForResult(Intent.createChooser(intent, "Select Picture"), ALBUM)
                        //                            showActivityForResult(intent,ALBUM);
                    }
                } catch (e: Exception) {

                }
            }
        }, 1, false).setData(photoList)
        mPhotoPop!!.showPopupWindow()
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, result: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            val options = UCrop.Options()
            options.setCompressionFormat(Bitmap.CompressFormat.JPEG)
            options.setCompressionQuality(100)
            if (requestCode == ALBUM && null != result && null != result.data) {
                if ("hold.jpeg" == fileName) {
                    cropPicture(options, result.data, Uri.fromFile(mFile), 1500, 1200)
                } else {
                    cropPicture(options, result.data, Uri.fromFile(mFile), 500, 500)
                }
            }
            if (requestCode == CAMERA) {
                mCropedFile = File(this.cacheDir.absolutePath, "/cropped.jpeg")
                if (!mCropedFile!!.exists()) {
                    try {
                        mCropedFile!!.createNewFile()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }

                }
                if ("hold.jpeg" == fileName) {
                    cropPicture(options, Uri.fromFile(mFile), Uri.fromFile(mCropedFile), 1500, 1200)
                } else {
                    cropPicture(options, Uri.fromFile(mFile), Uri.fromFile(mCropedFile), 500, 500)
                }

            }
        }

        if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            mUri = UCrop.getOutput(result!!)
            uploadImage(mUri!!)
        }
    }

    private fun uploadImage(uri: Uri) {
        var file: File? = null
        var type = ""
        try {
            file = File(URI(uri.toString()))
        } catch (e: URISyntaxException) {
            e.printStackTrace()
        }

        if (null != file) {
            if ("hold.jpeg" == fileName) {
                type = "hand"
            } else if ("front.jpeg" == fileName) {
                type = "positive"
            } else if ("reverse.jpeg" == fileName) {
                type = "back"
            }
            mPresenter.uploadPhoto(file, type, this)
        }
    }


    private fun cropPicture(options: UCrop.Options, data: Uri?, uri2: Uri, width: Int, height: Int) {
        UCrop.of(data!!, uri2)
                .withAspectRatio(1f, 1f)
                .withMaxResultSize(width, height)
                .withOptions(options)
                .start(this)
    }

    override fun submitSuccess() {
//        ToastUtils.show(this@CertificationActivity, getString(R.string.提交成功))
        toast(getString(R.string.提交成功))
        EventBus.getDefault().post(AuditSuccessEvent())
        finish()
    }

    override fun loadSuccess(bean: UploadFileBean) {

        if ("hold.jpeg" == fileName) {
            holdPath = bean.data!!.fileUrl
            setPhotoByUri(holdPath, holdPhoto)
            item_hold.findViewById<LinearLayout>(R.id.ll_camera).visibility = View.GONE
        } else if ("front.jpeg" == fileName) {
            frontPath = bean.data!!.fileUrl

            setPhotoByUri(frontPath, frontPhoto)
            item_front.findViewById<LinearLayout>(R.id.ll_camera).visibility = View.GONE
        } else if ("reverse.jpeg" == fileName) {
            reversePath = bean.data!!.fileUrl

            setPhotoByUri(reversePath, reversePhoto)
            item_reverse.findViewById<LinearLayout>(R.id.ll_camera).visibility = View.GONE
        }
    }

    override fun loadFail() {

    }

    private fun setPhotoByUri(uri: String?, view: ImageView?) {

        Glide.with(this).load(RetorfitServiceManger.BASE_IMG_URL + uri!!)
                .apply(RequestOptions().centerCrop().placeholder(R.mipmap.kapian_renzhen))
                .into(view!!)

    }
}
